package com.uminho.egendme;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Button;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.SlidingDrawer.OnDrawerScrollListener;
import android.widget.TextView;
import com.uminho.http.InternalStorage;

import com.uminho.http.Webservice;
import com.uminho.tools.ApplicationContext;

/****c* egendme/Login
 * DESCRIPTION
 * Classe responsável por oferecer suporte à actividade Login
 *
 ****
 */

public class Login extends Activity {
	/** Called when the activity is first created. */
	ImageView login, register;
	Button confirmDialog;
	SlidingDrawer slidingDrawerLogin, slidingDrawerRegister ;
	TextView loginErrorDialog;
	Dialog dialog;
	Handler messages=null;
	ProgressDialog myProgressDialog = null;
	
	/****f* Login/onCreate
	 * DESCRIPTION
	 * Método executado para criar a actividade
	 * INPUTS
	 * Estado da aplicação
	 * RESULT
	 * Actividade criada
	 ****
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		setContentView(R.layout.login);
		
		ApplicationContext.c = this.getApplicationContext();
		//InternalStorage.deleteToken();
		//InternalStorage.saveToken("dfsdfsf");
		
		//test if toke exists
		final boolean tokenExists=InternalStorage.existsToken();
		if(tokenExists){
		Intent init = new Intent(this, Dashboard.class);
		init.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(init);
		this.finish();
		}
		
		//Set Buttons
		login = (ImageView) findViewById(R.id.login);
		register = (ImageView) findViewById(R.id.register);
		slidingDrawerLogin = (SlidingDrawer) findViewById(R.id.SlidingDrawerLogin);
		slidingDrawerRegister = (SlidingDrawer) findViewById(R.id.SlidingDrawerRegister);
		slidingDrawerLogin.open();

		
	        messages = new Handler() {
		        @Override
				public void handleMessage(Message msg) {
		        	loginErrorDialog = (TextView) dialog.findViewById(R.id.TextView_PwdProblem);
        			
		        	Log.d("Login Hander", "what: "+msg.what);
		        	int i = msg.what;
		        	 //i=1;
		        	if(i==1){
		        		//right password
		        		Intent dashboard = new Intent(Login.this, Dashboard.class);
		        		dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		        		startActivity(dashboard);
						dialog.dismiss();
						Login.this.finish();
		        	} 
		        	else if(i==-1){
		        			//connection problem
		        			loginErrorDialog.setText(getString(R.string.connection_error));
		        		}
		        		else if(i==-2){
		        			//wrong password
		        			loginErrorDialog.setText(getString(R.string.wrong_password));
		        			TextView password=(TextView) dialog.findViewById(R.id.EditText_password);
		        			password.setText("");
		        			
		        		}
		        		else if(i==-3){
		        			//error inserting values
		        			loginErrorDialog.setText(getString(R.string.insertion_error));
		        			/*TextView password=(TextView) dialog.findViewById(R.id.EditText_password);
		        			password.setText("");*/	
		        		}
		        		else if(i==-10){
		        			myProgressDialog.dismiss();
		        			String res = msg.getData().getString("result"); 
		        			if(res==null) res="";
		        			Log.d("Register result", res);
		        			if(res.equals("success")){
		        				Log.d("Register", "loging in");
		        				//success
		        				//loginErrorDialog.setText("");
		        				Intent searchActivity = new Intent(Login.this,
		        						Dashboard.class);
		        				searchActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		        				startActivity(searchActivity);
		        				finish();
		        				dialog.dismiss();
		        				}else{
		        					loginErrorDialog.setText(res);
		        			//TextView password=(TextView) dialog.findViewById(R.id.EditText_password);
		        			//password.setText("");
		        				}
		        			
		        			
		        		}
		        		/*else if(i==-11){
		        		 * loginErrorDialog = (TextView) dialog.findViewById(R.id.TextView_PwdProblem);
		        			myProgressDialog.dismiss();
		        			loginErrorDialog.setText(R.string.connection_error);
		        		}*/
		        		else Log.d("handler", msg.what+" ... "+msg.arg1);
		        	
		        	
		        }
		    };
		
		
		slidingDrawerLogin.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			public void onDrawerOpened() {

			}
		});

		slidingDrawerLogin.setOnDrawerCloseListener(new OnDrawerCloseListener() {

			public void onDrawerClosed() {
				slidingDrawerLogin.open();
			}
		});

		slidingDrawerLogin.setOnDrawerScrollListener(new OnDrawerScrollListener() {

			public void onScrollStarted() {


			}

			public void onScrollEnded() {
				if(tokenExists){
					Intent dashboard = new Intent(Login.this, Dashboard.class);
					dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(dashboard);
					Login.this.finish();
					return;
				}
				dialog = new Dialog(Login.this,R.style.WindowTitleBackground);
				dialog.setContentView(R.layout.logindialog);
				dialog.setTitle("Login");	
				loginErrorDialog = (TextView) dialog.findViewById(R.id.TextView_PwdProblem);
				confirmDialog = (Button)dialog.findViewById(R.id.confirmDialog);
				dialog.show();
			

				confirmDialog.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						
						myProgressDialog = ProgressDialog.show(Login.this, getString(R.string.loading), getString(R.string.doingLogin), true);			
						new Thread() {

							@Override
							public void run() {
								testLoggin();
								myProgressDialog.dismiss();
							}

							}.start();
							
							

					}
				});
			}
		});


		slidingDrawerRegister.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			public void onDrawerOpened() {
				slidingDrawerRegister.close();
				dialog = new Dialog(Login.this,R.style.WindowTitleBackground);
				dialog.setContentView(R.layout.register);
				dialog.setTitle("Register");	
				loginErrorDialog = (TextView) dialog.findViewById(R.id.TextView_PwdProblem);
				confirmDialog = (Button)dialog.findViewById(R.id.confirmDialog);
				dialog.show();
				confirmDialog.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
								doRegister();		
					}
				});
			}
		});

		slidingDrawerRegister.setOnDrawerCloseListener(new OnDrawerCloseListener() {

			public void onDrawerClosed() {

			}
		});

		slidingDrawerRegister.setOnDrawerScrollListener(new OnDrawerScrollListener() {

			public void onScrollStarted() {


			}

			public void onScrollEnded() {

			}
		});

	}
	
	/****f* Login/testLogin
	 * DESCRIPTION
	 * Método executado para tratar uma tentativa de introdução do login
	 * INPUTS
	 * Recebe os valores introduzidos
	 * RESULT
	 * Volta a pedir o login caso a tentativa de autenticação falhe ou encaminha para a actividade Dashboard
	 ****
	 */
	private boolean testLoggin(){
		TextView username=(TextView) dialog.findViewById(R.id.EditText_username);
		TextView password=(TextView) dialog.findViewById(R.id.EditText_password);
		
		//username or password empty
		if(username.length()<=0 && password.length()<=0){
			messages.sendEmptyMessage(-3);
			return false;
		}
		Webservice w = Webservice.getInstance();
		boolean res=false;
		try {
			res = w.login(username.getText().toString(), password.getText().toString(), this);
		} catch (Exception e) {
			//connection error
			messages.sendEmptyMessage(-1);
			return false;
		}
		
		if(!res){
			//wrong password or username
			messages.sendEmptyMessage(-2);
		}
		//correct login
		else messages.sendEmptyMessage(1);
		
		return res;
	}
	
	/****f* Login/doRegister
	 * DESCRIPTION
	 * Método executado para tratar uma tentativa de registo
	 * INPUTS
	 * Recebe os valores introduzidos
	 * RESULT
	 * Utilizador criado
	 ****
	 */
	private void doRegister(){
		final TextView username=(TextView) dialog.findViewById(R.id.EditText_username);
		final TextView password=(TextView) dialog.findViewById(R.id.EditText_password);
		final TextView confirmpassword=(TextView) dialog.findViewById(R.id.EditText_confirmpassword);
		final TextView email=(TextView) dialog.findViewById(R.id.EditText_email);
		
		final String result=getString(R.string.unknownerror);
		//empty field
		if(username.length()<=0 || password.length()<=0|| email.length()<=0){
			loginErrorDialog.setText(R.string.textfield_empty);
		}
		else if(password.length()<6){
			loginErrorDialog.setText(R.string.password_less_chars);
		}
		//different passwords
		else if(!password.getText().toString().equals(confirmpassword.getText().toString())){
			loginErrorDialog.setText(R.string.different_password);
		//other cases
		}else{
			
				myProgressDialog = ProgressDialog.show(Login.this, getString(R.string.loading), getString(R.string.doingLogin), true);			
				new Thread() {

					@Override
					public void run() {
						try {
							Webservice w = Webservice.getInstance();
							String res=w.Registo(username.getText().toString(), password.getText().toString(), email.getText().toString(), Login.this);
							if(res==null) {
								res=result;
								Log.d("Register result: ", "was null!!!");
							}
							//
							
							Message msg = messages.obtainMessage();
				            Bundle b = new Bundle(); 
				            b.putString("result", res); 
				            msg.setData(b); 
				            msg.what=-10;
				            try{
				            messages.handleMessage(msg);
				            }catch (Exception e) {
								//e.printStackTrace();
				            }
						} catch (Exception e) {
							e.printStackTrace();
							
						}
						
						
					}

					}.start();
			
		}
		
		
	}
	



	//		login.setOnClickListener(new OnClickListener() {
	//
	//			public void onClick(View v) {	
	//
	//				dialog = new Dialog(Login.this);
	//				dialog.setContentView(R.layout.logindialog);
	//				dialog.setTitle("Login");	
	//				loginErrorDialog = (TextView) dialog.findViewById(R.id.TextView_PwdProblem);
	//				confirmDialog = (Button)dialog.findViewById(R.id.confirmDialog);
	//				dialog.show();
	//
	//				confirmDialog.setOnClickListener(new OnClickListener() {
	//					public void onClick(View v) {
	//						//loginErrorDialog.setText("Erro!!");
	//						
	//						Intent dashboard = new Intent(Login.this, Dashboard.class);
	//						startActivity(dashboard);
	//						
	//					}
	//				});
	//			}
	//		});

	//		register.setOnClickListener(new OnClickListener() {
	//
	//			public void onClick(View v) {
	//
	//				//setContentView(R.layout.register);
	//				dialog = new Dialog(Login.this);
	//				dialog.setContentView(R.layout.register);
	//				dialog.setTitle("Register");	
	//				loginErrorDialog = (TextView) dialog.findViewById(R.id.TextView_PwdProblem);
	//				confirmDialog = (Button)dialog.findViewById(R.id.confirmDialog);
	//				dialog.show();
	//				confirmDialog.setOnClickListener(new OnClickListener() {
	//					public void onClick(View v) {
	//						//loginErrorDialog.setText("Erro!!");
	//
	//						Intent dashboard = new Intent(Login.this, Dashboard.class);
	//						startActivity(dashboard);
	//
	//					}
	//				});
	//			}
	//		});



}